<?php 

namespace app\wxapp\controller;
use think\Exception;
use think\Request;
use think\Db;
use app\common\model\Cars as CarsModel;
use app\common\model\CarsInfo;
use app\common\model\Terminal as TerminalModel;
use app\common\request\ClientLai;
use app\common\model\InstallDevices;
use app\common\model\InstallUser;
use app\common\model\Version;

class Terminal extends Base
{
    public function index()
    {       
        $request = Request::instance();
        $post = $request->post();
       
        if ( !empty($post['search_input']) ) {
            $where['cardcode|sim_id|equipment_id'] = ['like','%'.$post['search_input'].'%'];
                
        }
 
        if( empty($where) ){
            $where = '1=1';
        }        
        try {           
            $data = TerminalModel::where($where)
                        ->order('id', 'desc')
                        ->paginate($post['length'],false,[
                                'type'     => 'bootstrap',
                                'var_page' => 'page',
                                'page'=>$post['page'] ,
                            ]);             
        } catch (\Exception $e) {
            
            return [
                'code'=>2,
                'msg'=>$e->getMessage(),
                ];
        }
        return $data;
    }


    public function add(){
        $request = Request::instance();
        $param = $request->post();
        $result = Db::name('terminal')->where(['id'=>$param['tid'],'equipment_id'=>$param['equipment_id']])->field('equipment_id,sim_id,cardcode')->find();
        if($result){
            $cars = Db::name('cars')->where('equipment_id',$result['equipment_id'])->find();
            if($cars){

                $arr['result'] = 1;
                $arr['msg'] = '设备已绑定';
                
            }else{
                    
                try{
                    $result['supplier_no'] = $param['supplier_no']; 
                    $int = CarsModel::where('car_id', $param['car_id'])->update($result);
                    $data = Db::name('cars_info')->where(['car_unique_id'=>$param['car_unique_id']])->find();
                    if($data){
                        $res = Db::name('cars_info')->where('car_unique_id',$param['car_unique_id'])->setField('supplier_no',$param['supplier_no']);
                    }else{
                        $info = new CarsInfo;
                        $info->allowField(true)->save($param);

                    }
                    $model = new InstallDevices();
                    $devices = $model->allowField(true)->save($param);
                    
                    $arr['result'] = 0;
                    $arr['msg'] = '绑定成功';

                }catch(\Exception $e){
                    
                    $arr['result'] = 1;
                    $arr['msg'] = '绑定失败';
                }
            }

        }else{

            $arr['result'] = 1;
            $arr['msg'] = '设备不存在';
        }
        return $arr;
    }

    public function Version(){
        $request = Request::instance();
        $param = $request->post();
        $cars = CarsModel::where('car_unique_id',$param['car_unique_id'])->field('supplier_no,car_unique_id')->find();
        if($cars){
            if($cars['supplier_no'] == 1376920002){
                $config = config('gz_blt');
                $obj = new ClientLai($config['user_name'],$config['password']);
                $data['car_unique_id'] = $cars['car_unique_id'];                 
                $data['version'] = $param['version'];
                $res = $obj->request_post(rtrim($config['url'],'/').'/api/vehicle/updateTerminal',http_build_query($data));
                $arr = json_decode($res,true);
                
                if($arr['result'] == 0){
                    $result['status'] = 0;
                    $result['msg'] = '指令发送成功'; 
                }else{
                    $result['status'] = 1;
                    $result['msg'] = '指令发送失败'; 
                }
            }else if($cars['supplier_no'] == 1376920003){
                $config = config('local_iot');
                $obj = new ClientLai($config['user_name'],$config['password']);
                $res = $obj->request_post(rtrim($config['url'],'/').'/machineSoftware/upgradeDevice',['car_unique_id'=>$cars['car_unique_id'],'version'=>$param['version']]);
                $arr = json_decode($res,true);
               
                if($arr['result'] == 0){
                    $result['status'] = 0;
                    $result['msg'] = '指令发送成功'; 
                }else{
                    $result['status'] = 1;
                    $result['msg'] = '指令发送失败'; 
                }
            }else{
                $result['status'] = 1;
                $result['msg'] = '车机厂商不存在';
            }
        }else{
            $result['status'] = 1;
            $result['msg'] = '车架号不合法';
        }
        return $result;
    }

    public function register(){
        $config = config('local_iot');
        $obj = new ClientLai($config['user_name'],$config['password']);
        $request = Request::instance();
        $param = $request->param();
        
        try{

            $ternimal = Db::name('terminal')->field('equipment_id,status')->where(['id'=>$param['id']])->find();

        }catch(\Exception $e){

            $datum['result'] = 1;
            $datum['msg'] = $e->getMessage();

        }
            
        if($ternimal){
            if($ternimal['status']==1){
                
                $datum['result'] = 1;
                $datum['msg'] = '设备已注册';
                
            }else{
               
                try{
                    $data['device_name'] = $ternimal["equipment_id"];
                    $res = $obj->request_post(rtrim($config['url'],'/').'/device/registDevice',$data);
                    $arr = json_decode($res,true);

                    if($arr['result'] == 0){
                        foreach ($arr['data'] as $value){
                            if($value['success'] == true){
                                try{
                                    $val = Db::name('terminal')->where(['id'=>$param['id']])->update(['status'=>1]);
                                    if($val){
                                        $datum['result'] = 0;
                                        $datum['msg'] = '设备注册成功';
                                    }
                                }catch(\Exception $e){
                                    $datum['result'] = 1;
                                    $datum['msg'] = $e->getMessage(); 
                                }
                                
                            }elseif($value['success'] == false){
                                
                                $datum['result'] = 1;
                                $datum['msg'] = '设备已注册';
                            }
                        }
                    }else{
                        $datum['result'] = 1;
                        $datum['msg'] = $arr['msg']; 

                    }

                }catch(\Exception $e){
                    $datum['result'] = 1;
                    $datum['msg'] = $e->getMessage();
                }
            }

        }else{

            $datum['result'] = 1;
            $datum['msg'] = '设备不存在';

        }
        return $datum;
    }

    public function queryDeviceDetail(){
        $request = Request::instance();
        $param = $request->param();
        $result = Db::name('terminal')->where(['id'=>$param['id']])->find();
        if($result){
            $data['device_name'] = $result['equipment_id'];
            $config = config('local_iot');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $res = $obj->request_post(rtrim($config['url'],'/').'/device/queryDeviceDetail',$data);
            if($res){
                $arr = json_decode($res,true);
            
            }else{
                $arr = null;
            }
            $cars=null;
            if($arr['result']==0){
                $cars = CarsModel::where(['equipment_id'=>$result['equipment_id']])->field('band_status,car_unique_id,car_sn,supplier_no')->find();
            }else{
                $arr=null;
            }
        }
        $arr['cars'] = $cars;
        return $arr;
        
    }

    public function person(){
        $data = InstallUser::all();
        return $data;
    }

    public function getVersion(){
        $model = new Version();
        $version = $model->column('version');
        return $version;
    }

    public function installDetails($id=1){
        $data = InstallDevices::with('terminal,installUser')->where('car_id',$id)->find();
        $data['cars'] = CarsModel::get($id);
        return $data;
    }

    public function edit(){
        $request = Request::instance();
        $param = $request->post();
        $result = Db::name('terminal')->where(['id'=>$param['tid'],'equipment_id'=>$param['equipment_id']])->field('equipment_id,sim_id,cardcode')->find();
        if($result){
            $cars = Db::name('cars')->where('equipment_id',$result['equipment_id'])->find();
            if($cars){

                $arr['result'] = 1;
                $arr['msg'] = '设备已绑定';
                
            }else{

                $result['supplier_no'] = $param['supplier_no'];
                $model = new CarsModel(); 
                $install_devices = new InstallDevices();        
                try {
                                                
                    $result = $model->allowField(true)->save($result,['car_id' => $param['car_id']]);
                    CarsInfo::where('car_unique_id',$param['car_unique_id'])->update(['supplier_no'=>$param['supplier_no']]);
                    $int = $install_devices->allowField(true)->save($param,['car_id' => $param['car_id']]);
                    

                    $arr['result'] = 0;
                    $arr['msg'] = '更换成功';

                } catch (Exception $e) {
                
                    $arr['result'] = 1;
                    $arr['msg'] = '更换失败';
                }    
                
            }

        }else{

            $arr['result'] = 1;
            $arr['msg'] = '设备不存在';
        }           

        return $arr;
        
    }

    public function delete(){
        $request = Request::instance();
        $param = $request->param();
        try{

            $int = CarsModel::where('car_id', $param['car_id'])->update(['equipment_id'=>'','sim_id'=>'','cardcode'=>'','supplier_no'=>'']);
            $res = CarsInfo::where('car_unique_id',$param['car_unique_id'])->update(['supplier_no'=>'']);
            
            $arr['result'] = 0;
            $arr['msg'] = '更换成功';

        }catch(Exception $e){

            $arr['result'] = 0;
            $arr['msg'] = '更换失败';
        }
        return $arr;
    }
}